using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.IO;

/// <summary>
/// Summary description for AsymetricEncryptor
/// </summary>
public class AsymetricEncryptor
{
	#region [ ReadKey ]
	/// <summary>
	/// Reads the public key from XML file.
	/// </summary>
	/// <param name="publicKeyFilePath">The public key file path.</param>
	/// <param name="keyString">The public key string.</param>
	/// <param name="exeptionString">The exeption string.</param>
	/// <returns></returns>
	private static bool ReadKey(string publicKeyFilePath, out string keyString, out string exeptionString)
	{
		exeptionString = "00 no error";
		keyString = "";
		//tryinng to read from XML file
		try
		{
			keyString = File.ReadAllText(publicKeyFilePath, Encoding.UTF8);			
		}
		// catching all posible exceptions
		catch (FileNotFoundException)
		{
			exeptionString = "08 Publick keyFile not fond";
			return false;
		}
		catch (FileLoadException)
		{
			exeptionString = "09 keyFile loading error";
			return false;
		}
		catch (Exception)
		{
			exeptionString = "10 XML error";
			return false;
		}
		return true;
	}
	#endregion

	#region [ EncryptData ]
	/// <summary>
	/// Encrypts data with public key.
	/// </summary>
	/// <param name="data">The data to be encrypted.</param>
	/// <param name="publicKeyFilePath">The public key file path.</param>
	/// <param name="encryptedData">The encrypted data.</param>
	/// <param name="exeptionString">The exception string.</param>
	/// <returns></returns>
	public static bool EncryptData(string data, string publicKeyFilePath, out byte[] encryptedData, out string exceptionString)
	{
		string readKeyException="";
		string publicKey;
		exceptionString = "00 no error";
		encryptedData = null;

		// Reading public key from the XML file
		if (!ReadKey(publicKeyFilePath, out publicKey, out readKeyException))
		{
			exceptionString = readKeyException;
			return false;
		}

		// trying to ecrypt data using RSACryptoServiceProvider.Encrypt method
		try
		{
			RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
			rsa.FromXmlString(publicKey);
			encryptedData = rsa.Encrypt(Encoding.UTF8.GetBytes(data), true);
		}
		catch (CryptographicUnexpectedOperationException)
		{
			exceptionString = "11 Unexpected Cryptographic error";
			return false;
		}
		catch (CryptographicException)
		{
			exceptionString = "12 Cryptographic error";
			return false;
		}
		catch (Exception)
		{
			exceptionString = "13 General crypting error";
			return false;
		}
		return true;
	}
	#endregion
}

